package action

import (
	"github.com/kataras/iris/v12/context"
	"github.com/kataras/iris/v12/mvc"
	"github.com/xuri/excelize/v2"
	"net/http"
)

// ExportExcelResult 导出.xlsx格式
type ExportExcelResult struct {
	Data     [][]any  // 数据
	Header   []string // 表头
	FileName string   // 文件名
}

func ExportExcel(data [][]any, header []string) mvc.Result {
	return &ExportExcelResult{
		Data:   data,
		Header: header,
	}
}

// Dispatch writes the response result to the context's response writer.
func (r *ExportExcelResult) Dispatch(ctx *context.Context) {
	var statusCode = http.StatusInternalServerError
	// 默认出现错误
	defer func() {
		ctx.ResponseWriter().WriteHeader(statusCode)
	}()
	ctx.ResponseWriter().Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
	f := excelize.NewFile()
	defer f.Close()
	cell, err := excelize.CoordinatesToCellName(1, 1)
	if err != nil {
		systemLog.Errorln(err.Error())
		return
	}
	err = f.SetSheetRow("Sheet1", cell, &r.Header)
	if err != nil {
		systemLog.Errorln(err.Error())
		return
	}
	for index, item := range r.Data {
		cell, err := excelize.CoordinatesToCellName(1, index+2)
		if err != nil {
			systemLog.Errorln(err.Error())
			return
		}
		err = f.SetSheetRow("Sheet1", cell, &item)
		if err != nil {
			systemLog.Errorln(err.Error())
			return
		}
	}
	err = f.Write(ctx.ResponseWriter())
	if err != nil {
		systemLog.Errorln(err.Error())
		return
	}
	statusCode = http.StatusOK
}
